//
//  MGProfileController.m
//  Decorate-iOS
//
//  Created by yyb on 2022/8/12.
//  Copyright © 2022 Moneyease Co., LTD. All rights reserved.
//

#import "MGProfileController.h"
#import "MGProfileInputController.h"

#import "MGProfileAvatarCell.h"
#import "MGProfileInputCell.h"

#import <YYBBaseViews/YYBPermission.h>
#import <YYBBaseViews/YYBPhotoViewController.h>

@interface MGProfileController () <YYBPhotoViewControllerDelegate>
@property (nonatomic, strong) UIImage *updateAvatar;

@end

@implementation MGProfileController

- (void)viewDidLoad {
    [super viewDidLoad];
}

- (void)beginCreateNotifications {
    @weakify(self);
    [[[NSNotificationCenter defaultCenter] rac_addObserverForName:YYBUserUpdateNotifictaion object:nil]
     subscribeNext:^(NSNotification * _Nullable x) {
        @strongify(self);
        [self.tableView reloadData];
    }];
}

- (void)showPhotoPickerView {
    YYBPhotoViewController *vc = [[YYBPhotoViewController alloc] init];
    vc.delegate = self;
    vc.isProduceAsUIImage = YES;
    
    vc.modalPresentationStyle = UIModalPresentationFullScreen;
    [self presentViewController:vc animated:YES completion:nil];
}

- (void)submitUserAvatar {
    @weakify(self);
    self.refreshAlertView = [YYBAlertView showQueryStringAlertViewWithString:@"更新中" inView:self.view isResizeContainer:NO];
    [MGOssManager.shared uploadAvatar:self.updateAvatar completeBlock:^(NSString * _Nonnull key) {
        @strongify(self);
        [MGReqManager.shared putUserAvatar:key successBlock:^(id data, NSDictionary *params) {
            [self.refreshAlertView closeAlertView];
            [MGUserModel updateUserAvatar:key];
            [self.tableView reloadData];
        } errorBlock:^(NSError *error, NSDictionary *params) {
            [self.refreshAlertView closeAlertView];
            [YYBAlertView showAlertViewWithError:error];
        }];
    } errorBlock:^(NSError * _Nonnull error) {
        @strongify(self);
        [self.refreshAlertView closeAlertView];
        [YYBAlertView showAlertViewWithError:error];
    }];
}

- (void)photoView:(YYBPhotoViewController *)photoView didCompleteFetchAssets:(NSArray *)assets originalAssets:(NSArray *)originalAssets {
    self.updateAvatar = assets.firstObject;
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
    [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
    [self submitUserAvatar];
    
    [photoView dismissViewControllerAnimated:YES completion:nil];
}

- (NSArray<NSString *> *)dequeueCellIdentifiers {
    return @[@"MGProfileAvatarCell", @"MGProfileInputCell", @"UITableViewCell"];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0 && indexPath.row == 0) {
        return 60;
    } else if (indexPath.row == 0) {
        return 20;
    }
    return 50;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            MGProfileAvatarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGProfileAvatarCell"];
            
            NSString *avatar = [MGReqManager.shared avatarURL:[MGUserModel user].avatar];
            [cell configViewWithDataModel:avatar];
            [cell configViewWithCornerType:MGCornerTypeTop];
            return cell;
        } else if (indexPath.row == 1) {
            MGProfileInputCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGProfileInputCell"];
            
            [cell configViewWithTitleValue:@"昵称" detailValue:[MGUserModel user].nick_name];
            [cell configViewWithCornerType:MGCornerTypeBottom];
            return cell;
        }
    } else if (indexPath.section == 1) {
        if (indexPath.row == 0) {
            UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell"];
            cell.backgroundColor = [UIColor clearColor];
            return cell;
        } else if (indexPath.row == 1) {
            MGProfileInputCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MGProfileInputCell"];
            
            [cell configViewWithTitleValue:@"注销账号" detailValue:nil];
            [cell configViewWithCornerType:MGCornerTypeAll];
            return cell;
        }
    }
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    @weakify(self);
    if (indexPath.section == 0) {
        if (indexPath.row == 0) {
            [YYBPermission photoPermissionWithCompleteBlock:^{
                @strongify(self);
                [self showPhotoPickerView];
            }];
        } else if (indexPath.row == 1) {
            [YYBViewRouter openOnClass:[MGProfileInputController class]];
        }
    } else if (indexPath.section == 1 && indexPath.row == 1) {
        [YYBAlertView showAlertViewWithTitle:@"注销账号" detail:@"确定要注销这个账号吗？注销后，所有的数据将会被删除，包括预算的数据。" firstActionTitle:@"取消" firstActionTapedBlock:nil secondActionTitle:@"确定" secondActionTapedBlock:^{
            @strongify(self);
            self.refreshAlertView = [YYBAlertView showQueryStringAlertViewWithString:@"注销中" inView:nil isResizeContainer:NO];
            [MGReqManager.shared deleteUserWithSuccessBlock:^(id data, NSDictionary *params) {
                [self.refreshAlertView closeAlertView];
                [YYBAlertView showAlertViewWithStatusString:@"账号已注销"];
                [self.navigationController popViewControllerAnimated:YES];
                [MGUserModel doUserLogout];
            } errorBlock:^(NSError *error, NSDictionary *params) {
                [self.refreshAlertView closeAlertView];
                [YYBAlertView showAlertViewWithError:error];
            }];
        }];
    }
}

- (NSString *)customPageTitle {
    return @"用户信息";
}

- (UIEdgeInsets)handleEdgeInsets {
    UIEdgeInsets insets = [super handleEdgeInsets];
    insets.top += 15;
    return insets;
}

@end
